/**
 * Project: complex.java
 * 
 * File Created at 2011-3-21
 * $Id: CompilerAPITester.java 137 2011-03-23 06:18:04Z ymkyve501@163.com $
 * 
 * Copyright 1999-2100 Alibaba.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package complex.java.compiler;

import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;

public class CompilerAPITester {

    private static String JAVA_SOURCE_FILE = "DynamicObject.java";
    private static String JAVA_CLASS_FILE  = "DynamicObject.class";
    private static String JAVA_CLASS_NAME  = "DynamicObject";

    public static void main(String[] args) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        generateJavaClass();
        try {

            Iterable sourcefiles = fileManager.getJavaFileObjects(JAVA_SOURCE_FILE);
            compiler.getTask(null, fileManager, null, null, null, sourcefiles).call();
            fileManager.close();
            
            test ();
            //创建动态编译得到的DynamicObject类的实例 
            //Class.forName(JAVA_CLASS_NAME).newInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void generateJavaClass() {
        try {
            FileWriter fw = new FileWriter(JAVA_SOURCE_FILE);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("public class " + JAVA_CLASS_NAME + "{");
            bw.newLine();
            bw.write("public "
                    + "void echo"
                    + "(){System.out.println(\"In the                 constructor of DynamicObject\");}}");
            bw.flush();
            bw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    private static void test ()throws Exception{
    	FileClassLoader loader = new FileClassLoader();  
        Class objClass = loader.loadClass(JAVA_CLASS_NAME);
        //Object obj = objClass.newInstance();  
       
        Method m = objClass.getMethod("echo", null);
        Object o = objClass.newInstance();  
        m.invoke(o);  
    }
}
